const express = require('express');
const router = express.Router();
const staff = require('../sql/staff');

router.get('/',function(req,res,next){
    staff.find({},(err,data)=>{
        if(err) {
          console.log(err)
        }
        res.render("staff",{
          index:3,
          data:data,
        })
    })

})

// 查询员工
router.get("/search", (req, res, next) => {
  const obj = req.query;
  let reg = new RegExp(obj.search);
  staff.find({username:reg},(err,data)=>{
      if(err){
          console.log(err)
      }
      res.render("staff", {
          index: 3,
          data,
      });
  })
});


// 添加员工 先跳转到staffAdd
router.get('/add',function(req,res,next){
    res.render('staffAdd',{
        index:3,
    })
})


router.post('/addAction',function(req,res,next){
  const obj = req.body;
  staff.insertMany(obj,(err,data)=>{
    if(err){
      console.log(err);
    }
    res.redirect('/staff')
  })
})

//删除员工
router.get('/delete',function(req,res,next){

  staff.deleteOne({_id:req.query._id},(err,data)=>{
    if(err){
      console.log(err);
    }
    res.redirect('/staff')
  })
})

//修改员工 跳转到staffUpdata.ejs
router.get('/update',function(req,res,next){
  const _id = req.query._id;
  staff.findById({_id:_id},(err,data)=>{
    if(err){
      console.log(err);
    }
    res.render('staffUpdata',{
      index:3,
      data,
    })
  })
})

router.post('/updateAction',function(req,res,next) {
  console.log('来到了真正删除里面')
  const obj = req.body 
  staff.findByIdAndUpdate(obj._id,obj,(err,data)=>{
      if(err) {
          console.log(err)
      }
      res.redirect('/staff')
  })
})


module.exports = router;

